package com.aps.apspda.activity;

import android.graphics.Canvas;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.PicEntity;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

public class PicViewActivity extends BaseActivity {


    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.pdfView)
    PDFView pdfView;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llProgress)
    LinearLayout llProgress;
    @BindView(R.id.llPDF)
    LinearLayout llPDF;
    @BindView(R.id.webview)
    WebView webView;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 将返回值回调到callBack的参数中
            switch (msg.what) {
                case 0:
                    pdfView.setVisibility(View.VISIBLE);
                    llProgress.setVisibility(View.GONE);
                    pdfView.fromStream((InputStream) msg.obj)
                            .enableSwipe(true)
                            .swipeHorizontal(false)
                            .enableDoubletap(true)
                            .defaultPage(0)
                            .onDraw(new OnDrawListener() {
                                @Override
                                public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

                                }
                            })
                            .onLoad(new OnLoadCompleteListener() {
                                @Override
                                public void loadComplete(int nbPages) {

                                }
                            })
                            .onPageChange(new OnPageChangeListener() {
                                @Override
                                public void onPageChanged(int page, int pageCount) {

                                }
                            })
                            .onPageScroll(new OnPageScrollListener() {
                                @Override
                                public void onPageScrolled(int page, float positionOffset) {

                                }
                            })
                            .onError(new OnErrorListener() {
                                @Override
                                public void onError(Throwable t) {
                                    AppUtils.saveErrorMessages(t, "加载PDF出错");
                                    ToastUtils.showFreeToast("PDF加载失败，请退出重试", PicViewActivity.this, false, Toast.LENGTH_SHORT);
                                }
                            })
                            .enableAnnotationRendering(false)
                            .password(null)
                            .scrollHandle(null)
                            .load();
                    break;
            }
        }
    };


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pic_view;
    }

    @Override
    protected void initView() {
        topView.setTitle("焊线图(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
    }

    @Override
    protected void initData() {
        String pic = getIntent().getStringExtra("pic");
        String picVersion = getIntent().getStringExtra("picVersion");
        requestData(pic, picVersion);
    }

    private void requestData(String pic, String picVersion) {
        EntityCallBack<BaseEntity<PicEntity>> callBack = new DialogEntityCallBack<BaseEntity<PicEntity>>
                (new TypeToken<BaseEntity<PicEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<PicEntity>> response) {
                if (response.body().isSuccess(PicViewActivity.this)) {
                    String fileName = response.body().getData().getRetureFileName().toLowerCase();
                    if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
                            || fileName.endsWith(".bmp")
                            || fileName.endsWith(".png")
                            || fileName.endsWith(".gif")) {
                        llPDF.setVisibility(View.GONE);
                        webView.setVisibility(View.VISIBLE);

                        webView.getSettings().setDefaultTextEncodingName("utf-8");
                        webView.getSettings().setAppCacheEnabled(true);// 设置启动缓存
                        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                        webView.getSettings().setLoadsImagesAutomatically(true);
                        webView.getSettings().setBlockNetworkImage(true);//拦截图片的加载，网页加载完成后再去除拦截
                        webView.getSettings().setJavaScriptEnabled(true);
                        webView.getSettings().setDisplayZoomControls(true);// 设置显示缩放按钮
                        webView.getSettings().setSupportZoom(true); // 支持缩放
                        webView.getSettings().setBuiltInZoomControls(true);

                        //方法一：
                        webView.getSettings().setUseWideViewPort(true);//让webview读取网页设置的viewport，pc版网页
                        webView.getSettings().setLoadWithOverviewMode(true);

                        //方法二：
//                        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//适应内容大小
                        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//适应屏幕，内容将自动缩放
                        AppUtils.saveErrorMessages("PIC URL is" + StaticMembers.PIC_URL + response.body().getData().getRetureFileName(), "日志记录");
                        webView.loadUrl(StaticMembers.PIC_URL + response.body().getData().getRetureFileName());
                    } else if (fileName.endsWith(".pdf")) {
                        llPDF.setVisibility(View.VISIBLE);
                        llProgress.setVisibility(View.VISIBLE);
                        pdfView.setVisibility(View.GONE);
                        webView.setVisibility(View.GONE);
//                        String name = "";
//                        try {
//                            name = java.net.URLEncoder.encode(response.body().getData().getRetureFileName(), "UTF-8");
//                        } catch (UnsupportedEncodingException e) {
//                            e.printStackTrace();
//                        }
                        NetUtils.getInputStreamFromUrl(
                                StaticMembers.PIC_URL + response.body().getData().getRetureFileName(),
                                handler);
                    }
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            PicViewActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<PicEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "WeldingDrawing");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("htmlfileName", pic);
        map.put("DiagramVersion", picVersion);
        NetUtils.requestNet(this, "/WeldingDrawing", map, callBack);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }
}
